const {
  ActivityModel
} = require('../../../utils/activity-model.js')
const activityModel = new ActivityModel()
const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
var utils = require("../../../utils/util.js");
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activityId: '', //活动id
    shopId: '', //门店id
    day: '0',
    hou: '00',
    min: "00",
    sec: "00",
    timerName: "", //计时器名字
    goodsList: [],
    authShow: false,
    activityStatus: 0,
    isLogin: false,
    productId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      activityId: options.activityId,
      shopId: options.shopId
    })
  },

  /**
   * 商品列表
   */
  getBargainMemberDetail: function () {
    var that = this;
    let request = null
    let param = {
      merchantId: wx.getStorageSync('merchantId'),
      activityId: that.data.activityId, //活动id
      shopId: that.data.shopId //门店id
    }
    if (that.data.isLogin) {
      request = activityModel.bargainMemberDetailLogin(param)
    } else {
      request = activityModel.bargainMemberDetailUnlogin(param)
    }
    request.then(data => {
      const goodsData = (data.queryAppletMemberGoodsResultList || []).map(item => {
        return {
          ...item,
          joinNum: utils.formatCurrency(item.joinNum) || 0,
          stock: utils.formatCurrency(item.stock) || 0,
        }
      })
      that.setData({
        activityStatus: 1,
        goodsList: goodsData || [],
        activityEnd: data.activityEnd.replace(/-/g, '/') || ''
      }, function () {
        var nowTime = new Date().getTime(); //现在时间（时间戳）
        var roundEndTime = new Date(that.data.activityEnd).getTime();
        if (that.data.activityEnd != "" && roundEndTime > nowTime) {
          that.countDown()
        }
      })
    }).catch(err => {
      if (err.status == 400) {
        that.setData({
          activityStatus: 2,
        })
      }
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 跳转到详情页面
   * 商品状态（会员登录后判断状态）
   * 1 初始状态（有库存，有剩余次数，未成功，砍价成功已经支付且有剩余次数)
   * 2 砍价成功已经支付且无剩余次数
   * 3 砍价成功未支付
   * 4 已售罄
   */
  goDetails: function (e) {
    let that = this
    const options = e.currentTarget.dataset.options || {}
    that.setData({
      productId: options.productId
    })
    if (options.productStatus != 4) {
      if (that.data.isLogin) {
        let param = {
          activityId: that.data.activityId,
          productId: options.productId,
          source: '点击单个套餐砍价'
        }
        let merchantId = wx.getStorageSync('merchantId')
        app.setTrackerLog(merchantId, 1, 4, 2, param)
        wx.navigateTo({
          url: '/activityBargain/bargain/details/index?activityId=' + that.data.activityId + '&productId=' + options.productId
        })
      } else {
        that.setData({
          authShow: true
        })
      }
    }
  },

  /**
   *微信会员信息
   */
  getUserInfo: function () {
    var that = this;
    memberModel.userInfo({
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      wx.setStorageSync('memberId', data.memberId);
      that.setData({
        memberId: data.memberId || "", //会员ID
      }, function () {
        that.getBargainMemberDetail();
      });
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 授权成功的回调
  loginSucceed: function () {
    let that = this
    app.getInfo().then(data => {
      that.setData({
        isLogin: data.data.login
      }, function () {
        that.getUserInfo()
      })
    })
  },
  // 倒计时
  countDown: function () {
    var that = this;
    var nowTime = new Date().getTime(); //现在时间（时间戳）
    var endTime = new Date(that.data.activityEnd).getTime(); //结束时间（时间戳）
    var time = (endTime - nowTime) / 1000; //距离结束的毫秒数
    // 获取天、时、分、秒
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    day = that.timeFormin(day);
    hou = that.timeFormin(hou);
    min = that.timeFormin(min);
    sec = that.timeFormin(sec);
    that.setData({
      day: that.timeFormat(day),
      hou: that.timeFormat(hou),
      min: that.timeFormat(min),
      sec: that.timeFormat(sec)
    })
    // 每1000ms刷新一次
    if (time > 0) {
      that.setData({
        countDown: true
      })
      that.setData({
        timerName: setTimeout(function () { //这里把setInterval赋值给变量名为timer的变量
          that.countDown()
        }, 1000)
      })
    } else {
      that.getBargainMemberDetail();
      clearInterval(that.data.timerName);
      that.setData({
        countDown: false
      })
    }
  },
  //小于10的格式化函数（2变成02）
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //小于0的格式化函数（不会出现负数）
  timeFormin(param) {
    return param < 0 ? 0 : param;
  },
  //跳转到首页
  goHome: function () {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    app.getInfo().then(data => {
      that.setData({
        isLogin: data.data.login
      }, function () {
        that.getBargainMemberDetail()
        let param = {
          activityId: that.data.activityId,
          source: '砍价专区页面'
        }
        let merchantId = wx.getStorageSync('merchantId')
        app.setTrackerLog(merchantId, 1, 4, 1, param)
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.timerName);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timerName);
  },
})